package com.kitty.game.activity.service.task;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.ActivityService;
import com.kitty.game.base.service.BagService;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossNpcParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.config.GameMap;
import com.kitty.game.config.MapBossPos;
import com.kitty.game.config.NPC;
import com.kitty.game.config.TaskSet;
import com.kitty.game.enter.Position;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.map.service.MapService;
import com.kitty.game.npc.message.RespAutoWalk;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.task.TaskDataPool;
import com.kitty.game.task.message.vo.TaskInfo;
import com.kitty.game.task.model.product.TaskType;
import com.kitty.game.task.service.NewTaskService;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.Const;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.util.NutMap;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 除暴任务处理类
 */
@Component
@Slf4j
public class ChuBaoTaskHandler extends TaskActivityHandler {
    // TODO 暂时先这样写，后续再优化
    /**
     * 除暴出现地图
     */
    private static final int[] MAPIDS = {2000, 3000, 4000, 24000, 6000, 8000, 9000, 8100/*, 8200*/};//除暴
    private static final String[] BOSS_NAMES = {"强盗", "土匪"};
    private static final List<String> SMALL_BOOS_NAMES = Arrays.asList("强盗", "喽罗", "帮凶", "土匪");
    private static final String[] POSTFIX_NAMES = {
            "刘霸天", "郑铁头", "张恶才", "吴天亮", "梅辛甘", "刘二狗", "刘为财", "刘一手", "刘三斤", "刘大虎",
            "刘二虎", "刘恶狗", "刘二胖", "刘心甘", "郑铁头", "郑发财", "郑天吼", "郑二狗", "郑狗财", "郑恶才",
            "张恶才", "张大嘴", "张辛甘", "张铁辛", "张大头", "吴天亮", "吴辛甘", "吴有财", "吴辛眼", "吴二狗",
            "吴铁蛋", "吴梅辛", "梅辛甘", "梅有才", "梅辛眼", "梅有钱", "涂霸心", "涂梅辛", "涂恶狗", "涂青龙",
            "涂白虎", "涂有角", "涂大脚", "甘铁心", "甘为狗", "甘二狗", "甘铁蛋", "甘大头", "钱眼开", "钱迷心",
            "钱心眼", "钱如命", "钱最大", "钱万能", "钱大山", "钱万贯", "钱开路", "钱世命", "钱狗财", "钱梅辛",
            "钱辛眼", "钱心迷", "钱大头", "易佰万", "易万圆", "易为难", "易从简", "赵为财", "赵霸天", "赵大炮",
            "赵大牛", "赵飞虎", "赵阿牛", "赵大头", "赵铁牛", "赵青龙", "赵白虎", "赵大胖", "赵二牛", "赵钱孙",
            "赵为钱", "李恶才", "李霸天", "李二胖", "李飞刀", "李大头", "李大胖", "李小胖", "石万元", "石霸恶",
            "石八盘", "石辛眼", "石大头", "石铁牛", "石铁头", "石大杜", "石小牛", "石二黑", "石大胖", "石二胖",
            "陈天才", "陈老三", "陈前后", "陈左右", "陈前因", "陈后果", "黄世仁", "黄扒皮", "黄万恶", "周扒皮",
            "周黑蛋", "周铁蛋", "周全胜", "周为全", "周阿牛", "周大头", "周铁头", "周不全", "孙八两", "孙二狗",
            "孙阿牛", "孙不二", "孙子背", "孙大汉", "孙老钱", "孙分熟", "胡一刀", "胡大个", "胡铁牛", "胡元霸",
            "胡周里", "胡青牛", "胡涂蛋", "胡涂重", "胡一恶", "胡万能", "胡爱财", "胡大头", "胡阿牛", "胡言语",
            "胡言来", "杜眼龙", "杜心眼", "杜一丁", "杜一两", "杜是非"};

    /**
     * 出现的方向
     */
    private static final short DIRECTION = 6;
    /**
     * 持续显示的秒数
     */
    private static final int SHOW_TIME_SEC = 15 * 60;
    private static final String CONTENT = "想抓我得先问问我手中的家伙答不答应。[就是来抓你的/" + NpcButton.DO_CHUBAO.getKey() + "][我先准备准备]";

    private static final String MESSAGE_TEMPLATE = "现有#Y%s#n在#R#Z%s#Z#n附近为非作歹，速去将其缉拿归案。";

    private static final int ACCEPT_MIN_LEVEL = 20;

    private static final String LEVEL_NOT_ENOUGH = "#Y{0}#n角色等级低于#R{1}级#n，等有足够的实力再来吧！[离开]";
    private static final String REMAIN_COUNT_NOT_ENOUGH = "你今日已抓捕了{0}次强盗，还是先去休息休息吧。[离开]";
    private static final String ACCEPTED = "你已经领取#R为民除暴#n任务，还不快去缉拿歹徒。[离开]";
    /**
     * Boss从属于别的玩家时的提示
     */
    private static final String NOT_YOU = "是不是活的不耐烦了想找死啊！[离开]";
    /**
     * 在战斗状态中的提示
     */
    private static final String IN_FIGHT = "等我收拾完他们再来对付你。[离开]";
    private static final String MEMBER_LEVEL_NOT_ENOUGH = "竟然还找#Y{0}#n来做帮手，不和你们玩！[离开]";

    @Override
    public TaskSet getAcceptingTask(Role role, NPC npc) {
        return taskService.getTaskSet(TaskDataPool.CHU_BAO_TASKID, role);
    }

    @Override
    public String canAcceptTask(Role role, TaskSet taskSet, boolean auto) {
        Team team = SpringUtils.getBean(TeamService.class).getTeam(role.getRoleId());
        if (teamService.isInTeam(role) == false) {
            /**个人*/
            /**等级不足*/
            if (role.getLevel() < ACCEPT_MIN_LEVEL) {
                return MessageFormat.format(LEVEL_NOT_ENOUGH, role.getName(), ACCEPT_MIN_LEVEL);
            }

            ActivityService activityService = SpringUtils.getBean(ActivityService.class);
            int remainCount = activityService.getRemainCount(role, ActivityType.CHU_BAO_TASK);
            /**剩余次数没有了*/
            if (remainCount <= 0) {
                return MessageFormat.format(REMAIN_COUNT_NOT_ENOUGH, ActivityType.CHU_BAO_TASK.getTotalCount());
            }

            /**已经接取了*/
            int taskId = TaskDataPool.CHU_BAO_TASKID;
            if (role.getTask().isAccepted(taskId)) {
                return ACCEPTED;
            }
        } else {
            /**组队*/

            /**不是队长时，不能操作*/
            if (team.isLeader(role.getRoleId()) == false) {
                /**这里返回空字符串方便判断是否不能操作*/
                return "";
            }

            /**有队员等级不足*/
            for (Member member : team.getList()) {
                if (member == null) {
                    continue;
                }
                /**暂离的不用判断*/
                if (member.isInTeam() == false) {
                    continue;
                }

                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                if (memberRole == null) {
                    continue;
                }

                if (memberRole.getLevel() < ACCEPT_MIN_LEVEL) {
                    return MessageFormat.format(LEVEL_NOT_ENOUGH, memberRole.getName(), ACCEPT_MIN_LEVEL);
                }
            }

            ActivityService activityService = SpringUtils.getBean(ActivityService.class);

            /**判断是否所有成员都没有次数了，都没有次数时则不能再接取*/
            boolean isMemberHaveCount = false;
            for (Member member : team.getList()) {
                if (member == null) {
                    continue;
                }
                /**暂离的不用判断*/
                if (member.isInTeam() == false) {
                    continue;
                }

                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                if (memberRole == null) {
                    continue;
                }

                int remainCount = activityService.getRemainCount(role, ActivityType.CHU_BAO_TASK);
                if (remainCount > 0) {
                    /**有一个成员有次数的时候就设置为true*/
                    isMemberHaveCount = true;
                    break;
                }
            }

            /**此时表示都没有次数*/
            if (isMemberHaveCount == false) {
                return MessageFormat.format(REMAIN_COUNT_NOT_ENOUGH, ActivityType.CHU_BAO_TASK.getTotalCount());
            }


            Role leader = SpringUtils.getRoleService().getOnlinePlayer(team.getLeaderUid());
            int npcId = leader.getTask().getTaskNpcId(TaskDataPool.CHU_BAO_TASKID);
            if (npcId > 0) {
                /**判断所有玩家的任务目标是一致的，是一致的，则返回已接取提示*/
                boolean isMemberOtherTarget = false;
                for (Member member : team.getList()) {
                    if (member == null) {
                        continue;
                    }
                    /**暂离的不用判断*/
                    if (member.isInTeam() == false) {
                        continue;
                    }

                    Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                    if (memberRole == null) {
                        continue;
                    }

                    int memberNpcId = memberRole.getTask().getTaskNpcId(TaskDataPool.CHU_BAO_TASKID);

                    /**有一个成员的目标NPC与队长的NPC不一致时，就设置为true*/
                    if (memberNpcId != npcId) {
                        isMemberOtherTarget = true;
                        break;
                    }
                }

                if (isMemberOtherTarget == false) {
                    return ACCEPTED;
                }
            }
        }

        return null;
    }

    @Override
    public void doBeforeAccept(Role role, TaskSet taskSet) {
        /**接取前先删除任务*/
        deleteTask(role, taskSet);
    }
    public void doAfterAccept(Role role, TaskSet taskSet) {
        super.doAfterAccept(role, taskSet);
        Team team = this.teamService.getTeam(role.getRoleId());
        if (!this.teamService.isInTeam(role) || team.isLeader(role.getRoleId())) {
            // 自动寻路到下一个NPC
            this.autoWalk(role, taskSet);
        }
    }
    // 自动导航到下一个任务
    private void autoWalk(Role role, TaskSet taskSet) {
        TaskInfo taskInfo = this.getTaskInfo(role, taskSet);
        if (taskInfo == null) {
            return;
        }
        RespAutoWalk respAutoWalk = new RespAutoWalk();
        respAutoWalk.setTaskName(taskInfo.getTaskName());
        respAutoWalk.setDest(taskInfo.getTaskZhiyin());
        MessagePusher.pushMessage(role, respAutoWalk);
    }
    @Override
    public TaskInfo getTaskInfo(Role role, TaskSet taskSet) {
        int taskNpcId = role.getTask().getTaskNpcId(taskSet.getId());
        MapService mapService = SpringUtils.getBean(MapService.class);
        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        NPC npc = mapService.getNpc(taskNpcId);
        if (npc == null) {
            log.error("{}的{}任务对应的{}npcId找不到NPC", role.getUid(), taskSet.getId(), taskNpcId);
            return null;
        }
        GameMap gameMap = mapService.getMap(npc.getMapId());
        int doStep = (activityService.getFinishCount(role, ActivityType.CHU_BAO_TASK) % 10) + 1;
        long remainMinute = (npc.getEndTime() > System.currentTimeMillis() ? ((npc.getEndTime() - System.currentTimeMillis()) / Const.MINUTE) : 0);
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setQuit((short) taskSet.getGiveUp());// 是否可以放弃
        taskInfo.setTaskName(taskSet.getTaskName());
        taskInfo.setShow_name(taskSet.getTaskName() + MessageFormat.format("({0}/10)", doStep));
        taskInfo.setTaskInfo(MessageFormat.format(taskSet.getTaskJieshao(), doStep, gameMap.getName(), npc.getName(), gameMap.getName(), npc.getX(), npc.getY(), remainMinute));
        taskInfo.setTaskZhiyin(MessageFormat.format(taskSet.getTaskZhiyin(), npc.getName(), gameMap.getName(), npc.getX(), npc.getY()));
        taskInfo.setTaskJiangli(taskSet.getTaskGift());
        return taskInfo;
    }

    @Override
    public String getPrompt(NPC npc) {
        GameMap map = SpringUtils.getBean(MapService.class).getMap(npc.getMapId());
        return String.format(MESSAGE_TEMPLATE, npc.getName(), map.getName());
    }

    @Override
    public BossNpcParam newBossNpcParam(Role role, TaskSet taskSet) {
        BossNpcParam bossNpcParam = new BossNpcParam();

        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        String randomBossName = getRandomBossName();
        BossSet bossSet = bossService.getBossSet(randomBossName);
        bossNpcParam.setNpcIcon(bossSet.getIcon());
        bossNpcParam.setBossSetName(bossSet.getName());


        int randomMapId = getRandomMapId();
        MapBossPos mapBossPos = bossService.getMapBossPos(randomMapId);
        Position position = bossService.getRandomPosition(mapBossPos);
        bossNpcParam.setMapId(mapBossPos.getMapId());
        bossNpcParam.setPosition(position);

        bossNpcParam.setDirection(DIRECTION);
        bossNpcParam.setShowTimeSec(SHOW_TIME_SEC);

        String randomPostfixName = getRandomPostfixName();
        String npcName = randomBossName + randomPostfixName;

        bossNpcParam.setNpcName(npcName);

        bossNpcParam.setNpcType(NPC.TYPE_CHU_BAO);
        /**属于哪个玩家*/
        bossNpcParam.setRoleUid(role.getUid());

        bossNpcParam.setBroad(true);


        return bossNpcParam;
    }

    @Override
    public String getNpcContent(Role role, NPC bossNpc) {
        String contentNotStart = getNpcContentNotFight(role, bossNpc);
        if (contentNotStart != null) {
            return contentNotStart;
        }

        return CONTENT;
    }

    public void sendNpcContent(Role role, NPC bossNpc) {
        String content = getNpcContent(role, bossNpc);
        SpringUtils.getNpcService().sendNpcContent(role, bossNpc, content);
    }

    /**
     * 获得随机的对应BossSet的name
     */
    private String getRandomBossName() {
        int index = ThreadLocalRandom.current().nextInt(BOSS_NAMES.length);
        return BOSS_NAMES[index];
    }

    /**
     * 获得随机出现的地图ID
     */
    private int getRandomMapId() {
        int index = ThreadLocalRandom.current().nextInt(MAPIDS.length);
        return MAPIDS[index];
    }

    /**
     * 获得随机的名字后缀
     */
    private String getRandomPostfixName() {
        int index = ThreadLocalRandom.current().nextInt(POSTFIX_NAMES.length);
        return POSTFIX_NAMES[index];
    }

    @Override
    public TaskType getTaskType() {
        return TaskType.CHU_BAO;
    }

    @Override
    public String getNpcContentNotFight(Role role, NPC bossNpc) {
        /**挑战玩家 不是对应玩家时*/
        if (bossNpc.getRoleUid() != role.getUid()) {
            /**在战斗状态时*/
            if (bossNpc.isInFight()) {
                return IN_FIGHT;
            }

            return NOT_YOU;
        }

        Team team = SpringUtils.getBean(TeamService.class).getTeam(role.getRoleId());
        if (teamService.isInTeam(role) == false) {
            /**个人*/
            /**等级不足*/
            if (role.getLevel() < ACCEPT_MIN_LEVEL) {
                return MessageFormat.format(MEMBER_LEVEL_NOT_ENOUGH, role.getName());
            }
        } else {
            /**组队*/
            for (Member member : team.getList()) {
                if (member == null) {
                    continue;
                }
                /**暂离的不用判断*/
                if (member.isInTeam() == false) {
                    continue;
                }

                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                if (memberRole == null) {
                    continue;
                }

                if (memberRole.getLevel() < ACCEPT_MIN_LEVEL) {
                    return MessageFormat.format(MEMBER_LEVEL_NOT_ENOUGH, memberRole.getName());
                }
            }
        }

        return null;
    }

    @Override
    public void doStartFight(Role role, TaskSet taskSet, NPC bossNpc) {
        List<BossParam> bossParamList = newBossParamList(role, bossNpc);
        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role), taskSet.getId(), bossNpc.getId());
        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        bossService.startFightToBoss(role, bossFightParam);
    }

    private List<BossParam> newBossParamList(Role role, NPC npc) {
        List<BossParam> bossParamList = new ArrayList<>();
        int count = getBossCount(role);

        /**npc对应的加在第1个*/
        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        BossSet bossSet = bossService.getBossSet(npc.getBossSetName());
        bossParamList.add(new BossParam(bossSet, npc.getName()));

        List<String> bossNames = new ArrayList<>();
        bossNames.addAll(SMALL_BOOS_NAMES);
        bossNames.remove(npc.getBossSetName());
        /**加count-1个*/
        for (int i = 1; i < count; i++) {
            int index = ThreadLocalRandom.current().nextInt(bossNames.size());
            bossSet = bossService.getBossSet(bossNames.get(index));
            bossParamList.add(new BossParam(bossSet, bossSet.getName()));
        }

        return bossParamList;
    }

    @Override
    protected int getFightType(Role role) {
        return Const.fightType_chubao;
    }

    @Override
    protected void addActivityFinishCount(Role role, TaskSet taskSet) {
        SpringUtils.getBean(ActivityService.class).addFinishCount(role, ActivityType.CHU_BAO_TASK, 1);
    }

    @Override
    protected void giveReward(Role role, NutMap reward, TaskSet taskSet, int currPetId) {


        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        int finishCount = activityService.getFinishCount(role, ActivityType.CHU_BAO_TASK);

        /**大于完成次数时，则不能再获得奖励*/
        if (finishCount > ActivityType.CHU_BAO_TASK.getTotalCount()) {
            log.info("不能获得除暴奖励，已大于完成次数|{}|{}", role.getUid(), finishCount);
            return;
        }

        int step = ((finishCount - 1) % 10 + 1);
        /**第10轮时*/
        if (step == 10) {
            // 奖励装备
            short roleLevel = role.getLevel();
            String temp = roleLevel + "";
            if (temp.length() == 3) {
                roleLevel = Short.parseShort(temp.substring(0, 2) + 0);
            } else {
                roleLevel = Short.parseShort(temp.substring(0, 1) + 0);
            }

            BagService bagService = SpringUtils.getBean(BagService.class);
            EquipService equipService = SpringUtils.getBean(EquipService.class);

            short newPos = bagService.getPos(role, false);
            if (newPos > 0) {
                equipService.getNotIdentifyEquip(roleLevel, role, newPos);
            }
        }

        int exp = new Double(role.getLevel() * reward.getInt("rewardExp", 0)
                * (step * 0.1 + 1)).intValue();
        int daohang = new Double(reward.getInt("rewardDaohang", 0)
                * ((step * 0.1 + 1))).intValue();
        int qianneng = new Double(reward.getInt("rewardQianneng", 0)
                * ((step * 0.1 + 1))).intValue();
        int money = new Double(reward.getInt("rewardMoney", 0)
                * ((step * 0.1 + 1))).intValue();

        PetService petService = SpringUtils.getBean(PetService.class);
        RoleService roleService = SpringUtils.getRoleService();
        Pet pet = petService.getPetById(role.getPetBox().getFightPetId(), role);
        if (pet != null) {
            currPetId=pet.getId();
            int petWuxue = new Double(reward.getInt("petRewardWuxue")
                    * ((step * 0.1 + 1))).intValue();
            NutMap doubleStatus = role.getPropsStatus();
            int point = doubleStatus.getInt("pet");
            if (doubleStatus.getInt("petStatus") == 1 && point >= 4) {
                doubleStatus.setv("pet", point - 4);
                role.save();
                petWuxue = petWuxue * 2;
            }
            roleService.addPetMatiral(role, pet, petWuxue);
        }

        int jijirulvling = role.getPropsStatus().getInt("manguaiStatus", 0);
        int kaiqi = role.getPropsStatus().getInt("manguai", 0);
        // 如果有急急如律令，奖励双倍
        if (jijirulvling > 0 && kaiqi > 0) {
            kaiqi = kaiqi - 1;
            int size = reward.getInt("size", 1);
            role.getPropsStatus().setv("manguai", kaiqi);
            money = money / size * 10;
            daohang = daohang / size * 10;
            qianneng = qianneng / size * 10;
        }
        NutMap nutMap = role.getPropsStatus();
        int point = nutMap.getInt("role");
        if (nutMap.getInt("roleStatus") == 1 && point >= 4) {
            nutMap.setv("role", point - 4);
            money = money * 2;
            daohang = daohang * 2;
            qianneng = qianneng * 2;
            exp = exp * 2;
        }
        //队长多给百分之5
        if(teamService.isTeamLeader(role)){
            daohang = (int)(daohang*1.05);
            qianneng = (int)(qianneng*1.05);
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("作为队长额外获得5%的道行、潜能。"));
        }
        roleService.addTao(role, daohang);
        roleService.addMoney(role, money);
        roleService.addPot(role, qianneng);
        roleService.addExp(role, exp, 20, currPetId);// 除暴 怪物按照20级算
        role.save();
    }

    @Override
    protected void doBeforeDelete(Role role, TaskSet taskSet) {

    }

    @Override
    protected void doAfterDelete(Role role, TaskSet taskSet) {
        boolean accepted = acceptTaskAtNpc(role, null, false);
        if (accepted) {
            Team team = teamService.getTeam(role.getRoleId());
            if (teamService.isInTeam(role) == false || team.isLeader(role.getRoleId())) {
                /**自动寻路战斗*/
                autoWalk(role);
            }
        }
    }

    @Override
    public boolean isCreateNpcForFight(TaskSet taskSet) {
        return true;
    }

    @Override
    public boolean isDeleteTaskTeamChange() {
        return true;
    }

    @Override
    public boolean isDeleteTaskLogout() {
        return true;
    }

    /**
     * 自动寻路战斗
     */
    public void autoWalk(Role role) {
        NewTaskService taskService = SpringUtils.getBean(NewTaskService.class);
        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.CHU_BAO_TASKID, role);
        TaskInfo taskInfo = getTaskInfo(role, taskSet);
        if (taskInfo == null) {return ;}

        RespAutoWalk respAutoWalk = new RespAutoWalk();
        respAutoWalk.setTaskName(taskInfo.getTaskName());
        respAutoWalk.setDest(taskInfo.getTaskZhiyin());
        MessagePusher.pushMessage(role, respAutoWalk);
    }
}
